package cn.cycleif.admin.service;

import cn.cycleif.app.mapper.AnswerMapper;
import cn.cycleif.app.mapper.QuestionMapper;
import cn.cycleif.entity.Answer;
import cn.cycleif.entity.Question;
import cn.cycleif.enums.ResultCodeEnum;
import cn.cycleif.util.R;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Date: 25/2/15-21:54
 * @Desc:
 */
@Service
public class AdminAnswerService extends ServiceImpl<AnswerMapper, Answer> {

  @Autowired
  private AnswerMapper   answerMapper;
  @Autowired
  private QuestionMapper questionMapper;

  @Transactional(rollbackFor = Exception.class)
  public R<String> acceptAnswer(Integer id) {
    Answer answer = answerMapper.selectById(id);
    if (answer == null) return R.error(ResultCodeEnum.ERROR_NOT_EXIST);
    answer.setAdopted(1);
    answerMapper.updateById(answer);

    LambdaQueryWrapper<Question> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(Question::getId, answer.getQuestionId());
    Question question = questionMapper.selectOne(wrapper);
    question.setAcceptedAnswerId(answer.getUserId());
    questionMapper.updateById(question);
    return R.success();
  }

  @Transactional(rollbackFor = Exception.class)
  public R<String> cancelAcceptAnswer(Integer id) {
    Answer answer = answerMapper.selectById(id);
    if (answer == null) return R.error(ResultCodeEnum.ERROR_NOT_EXIST);
    answer.setAdopted(0);
    answerMapper.updateById(answer);

    LambdaQueryWrapper<Question> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(Question::getId, answer.getQuestionId());
    Question question = questionMapper.selectOne(wrapper);
    question.setAcceptedAnswerId(null);
    questionMapper.updateById(question);
    return R.success();
  }
}
